/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public TreeNode increasingBST(TreeNode root) {
        TreeNode cur = root, pre = null;
        TreeNode head = null, tail = null;
        while (cur != null) {
            pre = cur.left;
            if (pre != null) {
                while (pre.right != null && pre.right != cur) {
                    pre = pre.right;
                }
                if (pre.right == null) {
                    pre.right = cur;
                    cur = cur.left;
                    continue;
                } else {
                    cur.left = null;
                }
            }
            if (head == null) {
                head = cur;
                tail = cur;
            } else {
                tail.right = cur;
                tail = cur;
            }
            cur = cur.right;
        }
        return head;
    }
}